package org.crown.project.api.utils;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.crown.common.jwt.JwtProperties;
import org.crown.common.jwt.JwtTokenUtil;
import org.crown.common.utils.HttpKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author wufengsheng
 */
@Slf4j
@Component
public class UserUtil {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtProperties jwtProperties;

    private Claims getClaims(){
        final String requestHeader = HttpKit.getRequest().getHeader(this.jwtProperties.getHeader());
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            Claims claims = this.jwtTokenUtil.getClaimFromToken(requestHeader.substring(7));
            if(claims != null){
                return claims;
            }
        }
        return null;
    }

    /**
     * 获取当前用户userId
     * @return
     */
    public synchronized Long getUserId() {
        Claims claims = this.getClaims();
        if(claims != null){
            String userId = "" + claims.get(jwtProperties.getUserId());
            if(userId != null && userId.length() != 0){
                return Long.valueOf(userId);
            }
        }
        return null;
    }

    /**
     * 获取当前用户openid
     * @return
     */
    public synchronized String getOpenId() {
        Claims claims = this.getClaims();
        if(claims != null){
            String openId = "" + claims.get(jwtProperties.getOpenId());
            if(openId != null && openId.length() != 0){
                return openId;
            }
        }
        return null;
    }
}
